package com.zscat.mallplus.market.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zscat.mallplus.annotation.IgnoreAuth;
import com.zscat.mallplus.annotation.SysLog;
import com.zscat.mallplus.fenxiao.entity.FenxiaoConfig;
import com.zscat.mallplus.fenxiao.mapper.FenxiaoConfigMapper;
import com.zscat.mallplus.pms.entity.*;
import com.zscat.mallplus.pms.service.*;
import com.zscat.mallplus.pms.vo.GoodsDetailResult;
import com.zscat.mallplus.ums.entity.UmsMember;
import com.zscat.mallplus.ums.entity.UmsMemberLevel;
import com.zscat.mallplus.ums.service.IUmsMemberLevelService;
import com.zscat.mallplus.ums.service.IUmsMemberService;
import com.zscat.mallplus.ums.service.RedisService;
import com.zscat.mallplus.ums.service.impl.RedisUtil;
import com.zscat.mallplus.util.IpAddressUtil;
import com.zscat.mallplus.util.JsonUtils;
import com.zscat.mallplus.util.WxContentUtils;
import com.zscat.mallplus.utils.CommonResult;
import com.zscat.mallplus.utils.ValidatorUtils;
import com.zscat.mallplus.vo.Rediskey;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 *
 * @Auther: rwz
 * @Date: 2020/09/18/1:00 上午
 * @Description:
 */
@Slf4j
@RestController
@Api(tags = "MarketProductController", description = "商品")
@RequestMapping("/api/market/product")
public class MarketProductController {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private RedisService redisService;

    @Resource
    private IPmsProductService productService;

    @Resource
    private IPmsProductCategoryService productCategoryService;

    @Resource
    private IUmsMemberService memberService;

    @Resource
    private IPmsFavoriteService favoriteService;

    @Resource
    private IUmsMemberLevelService memberLevelService;

    @Resource
    FenxiaoConfigMapper fenxiaoConfigMapper;

    @Resource
    private IPmsProductAttributeValueService productAttributeValueService;

    @Resource
    private IPmsCommentService commentService;

    @Resource
    private IPmsCommentReplayService commentReplayService;

    @Resource
    private IPmsCommentReportService commentReportService;

    @Resource
    private IPmsSkuStockService skuStockService;

    @Resource
    private IPmsFeightTemplateService feightTemplateService;

    @IgnoreAuth
    @ApiOperation(value = "查询商品分类")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = false, dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false, dataType = "int", paramType = "query", defaultValue = "10")
    })
    @SysLog(MODULE = "product", REMARK = "查询商品分类")
    @GetMapping(value = "catatoryList")
    public Object catatoryList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                               @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        return new CommonResult().success(productCategoryService.page(new Page<PmsProductCategory>(pageNum, pageSize), new QueryWrapper<PmsProductCategory>().eq("level", 0).eq("show_status", 1).orderByAsc("sort")));
    }

    @IgnoreAuth
    @ApiOperation(value = "查询商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "商品分类ID：不传值查询所有", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "productMajor", value = "商品大类：1->普通商品；2->积分商品；不传值查询所有", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "recommandStatus", value = "推荐状态：0->不推荐；1->推荐；不传值查询所有", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "storeId", value = "科技馆ID", required = false, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = false, dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false, dataType = "int", paramType = "query", defaultValue = "10")
    })
    @SysLog(MODULE = "product", REMARK = "查询商品列表")
    @GetMapping(value = "productList")
    public Object productList(@RequestParam(value = "categoryId", required = false) Long categoryId,
                              @RequestParam(value = "productMajor", required = false) Integer productMajor,
                              @RequestParam(value = "recommandStatus", required = false) Integer recommandStatus,
                              @RequestParam(value = "storeId", required = false) Integer storeId,
                              @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        Map map = new HashMap();
        if (ValidatorUtils.notEmpty(categoryId)) {
            map.put("categoryId", categoryId);
        }
        if (ValidatorUtils.notEmpty(productMajor)) {
            map.put("productMajor", productMajor);
        }
        if (ValidatorUtils.notEmpty(recommandStatus)) {
            map.put("recommandStatus", recommandStatus);
        }
        if (ValidatorUtils.notEmpty(storeId)) {
            map.put("storeId", storeId);
        }
        if (ValidatorUtils.notEmpty(pageNum)) {
            map.put("pageNum", pageNum);
        }
        if (ValidatorUtils.notEmpty(pageSize)) {
            map.put("pageSize", pageSize);
        }
        map.put("publishStatus", 1);
        map.put("verifyStatus", 1);
        map.put("deleteStatus", 1);
        List<PmsProduct> productList = new ArrayList<PmsProduct>();
        List<PmsProduct> products = productService.selectCategoryPorductList(map);
        for (PmsProduct product : products) {
            List<PmsSkuStock> skuStockList = skuStockService.list(new QueryWrapper<PmsSkuStock>().eq("product_id", product.getId()));
            product.setSkuStockList(skuStockList);
            productList.add(product);
        }
        return new CommonResult().success(productList);
    }

    @IgnoreAuth
    @ApiOperation(value = "查询商品属性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "productAttributeCategoryId", value = "商品属性分类编号", required = true, dataType = "int", paramType = "query")
    })
    @SysLog(MODULE = "product", REMARK = "查询商品属性")
    @GetMapping(value = "attributeList")
    public Object attributeList(@RequestParam(value = "productId", required = true) Long productId,
                                @RequestParam(value = "productAttributeCategoryId", required = true) Long productAttributeCategoryId) {
        Map map = new HashMap();
        map.put("productId", productId);
        map.put("productAttributeCategoryId", productAttributeCategoryId);
        return new CommonResult().success(productAttributeValueService.selectProductAttributeValue(map));
    }

    @ApiOperation(value = "商品评价")
    @SysLog(MODULE = "product", REMARK = "商品评价")
    @PostMapping(value = "comment")
    public Object comment(HttpServletRequest request,
                          PmsComment comment) {
    	
		Object object = WxContentUtils.Wxcontent(comment.getContent());
		if (object != null) {
			return object;
		}
        return commentService.saveComment(request, comment);
    }

    @ApiOperation(value = "评价回复")
    @SysLog(MODULE = "product", REMARK = "评价回复")
    @PostMapping(value = "commentReplay")
    public Object commentReplay(PmsCommentReplay commentReplay) {
        try {
            if (ValidatorUtils.empty(commentReplay.getCommentId())) {
                return new CommonResult().failed("ID不能为空");
            }
            if (ValidatorUtils.empty(commentReplay.getContent())) {
                return new CommonResult().failed("内容不能为空");
            }

            UmsMember currentMember = memberService.getNewCurrentMember();
            if (null != currentMember) {
                commentReplay.setMemberIcon(currentMember.getIcon());
                commentReplay.setMemberNickName(currentMember.getNickname());
            } else {
                return new CommonResult().failed("请先登录");
            }

            commentReplay.setCreateTime(new Date());
            commentReplay.setType(1);
            boolean isTrue = commentReplayService.save(commentReplay);
            if (isTrue) {
                return new CommonResult().success("回复成功");
            } else {
                return new CommonResult().failed("回复失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed(e.getMessage());
        }
    }

    @IgnoreAuth
    @ApiOperation(value = "查询商品评价列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "storeId", value = "科技馆ID", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "starStr", value = "评价等级字符串", required = false, dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "pageNum", value = "当前页", required = false, dataType = "int", paramType = "query", defaultValue = "1"),
            @ApiImplicitParam(name = "pageSize", value = "每页显示条数", required = false, dataType = "int", paramType = "query", defaultValue = "10")
    })
    @SysLog(MODULE = "product", REMARK = "查询商品评价列表")
    @GetMapping(value = "commentList")
    public Object commentList(@RequestParam(value = "productId", required = true) Long productId,
                              @RequestParam(value = "storeId", required = true) Integer storeId,
                              @RequestParam(value = "starStr", required = false) String starStr,
                              @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                              @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        if (ValidatorUtils.empty(productId)) {
            return new CommonResult().failed("商品ID不能为空");
        }

        if (ValidatorUtils.empty(storeId)) {
            return new CommonResult().failed("科技馆ID不能为空");
        }

        PmsComment comment = new PmsComment();
        comment.setProductId(productId);
        comment.setStoreId(storeId);
        if (ValidatorUtils.notEmpty(starStr)) {
            comment.setStarStr(starStr);
        }
        comment.setPageNum(pageNum);
        comment.setPageSize(pageSize);
        return new CommonResult().success(commentService.selectCommentList(comment));
    }

    /**
     * 根据ID查询商品详情
     *
     * @param id
     * @return
     */
    @IgnoreAuth
    @ApiOperation(value = "商品详情")
    @ApiImplicitParam(name = "id", value = "商品ID", required = true, dataType = "Long", paramType = "query")
    @SysLog(MODULE = "product", REMARK = "商品详情")
    @GetMapping(value = "detail")
    public Object detail(@RequestParam(value = "id", required = true, defaultValue = "0") Long id) {
        GoodsDetailResult goods = productService.getGoodsRedisById(id);;
//        try {
//            goods = JsonUtils.jsonToPojo(redisService.get(String.format(Rediskey.GOODSDETAIL, id + "")), GoodsDetailResult.class);
//            if (ValidatorUtils.empty(goods) || ValidatorUtils.empty(goods.getGoods())) {
//                log.info("redis缓存失效：" + id);
//                goods = productService.getGoodsRedisById(id);
//            }
//        } catch (Exception e) {
//            log.info("redis缓存失效：" + id);
//            goods = productService.getGoodsRedisById(id);
//        }
        if (goods == null) {
            return new CommonResult().failed("商品不存在");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("goods", goods);
        return new CommonResult().success(map);
    }

    @ApiOperation("根据规格选择商品库存信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "specStr", value = "规格字符串，用逗号隔开", required = false, dataType = "string", paramType = "query")
    })
    @SysLog(MODULE = "product", REMARK = "根据规格选择商品库存信息")
    @GetMapping(value = "getSkuStockPrice")
    public Object getSkuStockPrice(@RequestParam(value = "productId", required = true) Long productId,
                                   @RequestParam(value = "specStr", required = false) String specStr) {
        if (ValidatorUtils.empty(productId)) {
            return new CommonResult().failed("商品ID不能为空");
        }

        String[] specs = specStr.split(",");
        PmsSkuStock skuStock = new PmsSkuStock();
        skuStock.setProductId(productId);

        if (specs.length == 1) {
            skuStock.setSp1(specs[0]);
        } else if (specs.length == 2) {
            skuStock.setSp1(specs[0]);
            skuStock.setSp2(specs[1]);
        } else if (specs.length == 3) {
            skuStock.setSp1(specs[0]);
            skuStock.setSp2(specs[1]);
            skuStock.setSp3(specs[2]);
        } else if (specs.length == 4) {
            skuStock.setSp1(specs[0]);
            skuStock.setSp2(specs[1]);
            skuStock.setSp3(specs[2]);
            skuStock.setSp4(specs[3]);
        } else if (specs.length == 5) {
            skuStock.setSp1(specs[0]);
            skuStock.setSp2(specs[1]);
            skuStock.setSp3(specs[2]);
            skuStock.setSp4(specs[3]);
            skuStock.setSp5(specs[4]);
        } else {
            skuStock.setSp1(specs[0]);
            skuStock.setSp2(specs[1]);
            skuStock.setSp3(specs[2]);
            skuStock.setSp4(specs[3]);
            skuStock.setSp5(specs[4]);
            skuStock.setSp6(specs[5]);
        }

        return skuStockService.getOne(new QueryWrapper<>(skuStock));
    }

    @ApiOperation("获取商品运费")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "totalCount", value = "总数量", required = true, dataType = "double", paramType = "query")
    })
    @SysLog(MODULE = "product", REMARK = "获取商品运费")
    @GetMapping(value = "getFreight")
    public Object getFreight(@RequestParam(value = "productId", required = true) Long productId,
                             @RequestParam(value = "totalCount", required = true) Double totalCount) {
        String freight = "";
        // 根据商品ID查询商品详情
        PmsProduct product = productService.getById(productId);
        // 根据商品设置的运费模板ID查询运费模板详情
        PmsFeightTemplate feightTemplate = feightTemplateService.getById(product.getFeightTemplateId());
        if (null != feightTemplate) {
            if (feightTemplate.getFirstWeight().doubleValue() > totalCount) { // 商品总重量小于首重
                freight = feightTemplate.getFirstFee().toString();
            } else {
                freight = String.format("%.2f", feightTemplate.getFirstFee().doubleValue() + ((totalCount - feightTemplate.getFirstWeight().doubleValue()) * feightTemplate.getContinmeFee().doubleValue()));
            }
        }

        return new CommonResult().success(freight);
    }

    @ApiOperation(value = "同类推荐")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品分类ID", required = true, dataType = "long", paramType = "query"),
            @ApiImplicitParam(name = "storeId", value = "科技馆ID", required = true, dataType = "int", paramType = "query")
    })
    @SysLog(MODULE = "product", REMARK = "同类推荐")
    @GetMapping(value = "recommend")
    public Object recommend(@RequestParam(value = "id", required = true) Long id,
                            @RequestParam(value = "storeId", required = true) Integer storeId) {
        if (ValidatorUtils.empty(id)) {
            return new CommonResult().failed("商品分类ID不能为空");
        }
        if (ValidatorUtils.empty(storeId)) {
            return new CommonResult().failed("科技馆ID不能为空");
        }
        List<PmsProduct> productList = new ArrayList<PmsProduct>();
        List<PmsProduct> products = productService.list(new QueryWrapper<PmsProduct>().eq("product_category_id", id).eq("verify_status", 1).eq("publish_status", 1).eq("delete_status", 1).eq("store_id", storeId));
        Collections.shuffle(products);
        int count = 0;
        if (products.size() < 2) {
            count = products.size();
        }
        else {
            count = 2;
        }
        for (int i = 0; i < count; i ++) {
            PmsProduct product = (PmsProduct)products.get(i);
            productList.add(product);
        }
        return new CommonResult().success(productList);
    }

    @ApiOperation(value = "举报用户")
    @SysLog(MODULE = "product", REMARK = "举报用户")
    @PostMapping(value = "report")
    public Object report(PmsCommentReport commentReport) {
        try {
            if (ValidatorUtils.empty(commentReport.getMemberId())) {
                return new CommonResult().failed("被举报人ID不能为空");
            }

            if (ValidatorUtils.empty(commentReport.getReportContent())) {
                return new CommonResult().failed("举报内容不能为空");
            }

            UmsMember member = memberService.getNewCurrentMember();
            if (null != member) {
                commentReport.setCreatorId(member.getId());
                commentReport.setCreator(member.getNickname());
                commentReport.setCreatorPhone(member.getValidatePhone());
            } else {
                return new CommonResult().failed("请先登录");
            }

            // 根据被举报人ID查询被举报人用户信息
            UmsMember umsMember = memberService.getById(commentReport.getMemberId());
            commentReport.setMemberName(umsMember.getNickname());
            commentReport.setMemberPhone(umsMember.getValidatePhone());

            // 根据评论ID查询商品评论信息
            PmsComment comment = commentService.getById(commentReport.getCommentId());
            commentReport.setCommentContent(comment.getContent());
            commentReport.setCreateTime(new Date());

            boolean result = commentReportService.save(commentReport);
            if (result) {
                return new CommonResult().success("举报成功");
            } else {
                return new CommonResult().failed("举报失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new CommonResult().failed(e.getMessage());
        }
    }

    @IgnoreAuth
    @ApiOperation(value = "精品课程")
    @ApiImplicitParam(name = "storeId", value = "科技馆ID", required = false, dataType = "int", paramType = "query")
    @SysLog(MODULE = "product", REMARK = "精品课程")
    @GetMapping(value = "courseList")
    public Object courseList(@RequestParam(value = "storeId", required = false) Integer storeId) {
        PmsProduct product = new PmsProduct();
        product.setIsBoutique(1);
        if (ValidatorUtils.notEmpty(storeId)) {
            product.setStoreId(storeId);
        }
        product.setVerifyStatus(1);
        product.setDeleteStatus(1);
        List<PmsProduct> products = productService.list(new QueryWrapper<>(product).orderByDesc("create_time"));
        List<PmsProduct> productList = new ArrayList<PmsProduct>();
        for (PmsProduct pmsProduct : products) {
            // 根据商品ID查询商品库存
            List<PmsSkuStock> skuStockList = skuStockService.list(new QueryWrapper<PmsSkuStock>().eq("product_id", pmsProduct.getId()));
            pmsProduct.setSkuStockList(skuStockList);
            productList.add(pmsProduct);
        }
        return new CommonResult().success(productList);
    }
}
